/**
 * Created by mkDark on 2017/11/16.
 */
var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');

var YjxFavoriteModel = function(obj) {
    YjxBaseModel.call(this, obj);

    /**
     * CREATE TABLE `yjx_favorite` (
     `fav_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
     `user_id` bigint(20) NOT NULL COMMENT '用户id',
     `uni_item_id` bigint(20) NOT NULL COMMENT '统一项目id',
     `item_id` bigint(20) DEFAULT NULL COMMENT '商品id',
     `create_time` datetime NOT NULL,    创建时间
     `update_time` datetime NOT NULL,       修改时间
     `update_by` varchar(50) NOT NULL DEFAULT '',  创建人
     `del_flg` int(1) NOT NULL DEFAULT '0',   删除标记
     PRIMARY KEY (`fav_id`)
     ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户收藏表'
     */
};
YjxFavoriteModel.prototype = new YjxBaseModel();

// 取得表名
YjxFavoriteModel.prototype.getTableName = function(){
    return 'yjx_favorite';
};

// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxFavoriteModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'fav_id ='+ this.fav_id;
};

/**
 * 获取用户收藏表中有无收藏过
 * 添加模板到用户收藏
 * @author 毛凯
 * @date 2017-11-16
 * @param userId 用户唯一标识
 * @param tmplId 模板标识
 * @param callback
 *              qErr: 错误原因
 *              data： 0/1 0 标识未收藏过， 1 标志收藏过
 */

YjxFavoriteModel.prototype.checkUserFavTmplState = function(userId,tmplId,callback){

    // 从mysql中查询
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [checkUserFavTmplState] getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql ="SELECT	" +
            "	    COUNT(0) result	" +
            "	  FROM	" +
            "	    yjx.yjx_favorite	" +
            "	  WHERE user_id = "+userId+"	" +
            "	    AND uni_item_id = "+tmplId+ "	" +
            "	    AND del_flg = 0	";

        console.log(sql);
        // Use the connection
        connection.query(sql, function(qErr, res) {
            // And done with the connection.
            connection.release();
            var data = res[0].result;
            if(qErr) {
                console.log('YjxFavoriteModel.js [checkUserFavTmplState] qErr: ' +qErr);
            }
            // 回调
            callback(qErr, data);
        });
    });
};

/**
 * 取消用户收藏
 * @author 毛凯
 * @date 2017-11-16
 * @param userId  用户标识
 * @param tmplId  模板标识
 * @param callback
 *              qErr  错误信息
 */
YjxFavoriteModel.prototype.delTmplToFav = function(userId, tmplId, callback){
    // 从mysql中查询
    pool.pool.getConnection(function(getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [delTmplToFav] getConErr: '+getConErr);
            return callback(getConErr, null);
        }
        var sql = "	UPDATE	" +
            "	        yjx.yjx_favorite	" +
            "	    SET	" +
            "	        del_flg = 1	" +
            "	    WHERE uni_item_id = "+tmplId+ "	" +
            "	        AND user_id = "+userId+ "	" +
            "	        AND del_flg = 0	";
        console.log(sql);
        // Use the connection
        connection.query(sql, function(qErr, res) {
            // And done with the connection.
            connection.release();
            if(qErr) {
                console.log('YjxFavoriteModel.js [delTmplToFav] qErr: '+qErr);
            }
            // 回调
            callback(qErr);
        });
    });
};

/**
 * 获取用户收藏列表
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 用户对应收藏列表
 *
 * */
YjxFavoriteModel.prototype.getUserFavList = function (userId, pageNum, pageSize,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserFavList(false, userId, pageNum, pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取用户收藏个数
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId 用户标识
 * @param callback 回调
 *           err: 查询失败
 *           count: 用户收藏列表数量
 *
 * */
YjxFavoriteModel.prototype.getUserFavListCnt = function (userId,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavListCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserFavList(true, userId);
        console.log(sql);

        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavListCnt] queryErr' + queryErr);
                return callback(queryErr, null);
            }
            if (results && results[0]) {
                return callback(queryErr, results[0].count);
            }
            return callback(queryErr,null);
        });
    })

};

/**
 * 获取查询 用户收藏（列表/数量 ）的 sql
 *
 * @author 毛凯
 * @date   2017-11-17
 *
 * @param bForCnt true 获取用去收藏列表个数的 sql, false 标记获取列表的 sql
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 *
 * @return 对应类型的 sql
 * */
function sql_getUserFavList(bForCnt, userId, pageNum, pageSize) {

    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(0) as count ';
    } else  {
        sql +="	select	" +
            "	  res.*,	" +
            "	  IFNULL(uts.show_apply_cnt, 0) AS useCounts	"
    }
    sql +="	from	" +
        "	  (SELECT	" +
        "	    yui.uni_item_id AS id,	" +
        "	    vdd.design_name AS `name`,	" +
        "	    '2' AS opType,	" +
        "	    vdd.theme_thumb AS thumb,	" +
        "	    ts.width AS w,	" +
        "	    ts.height AS h,	" +
        "	    iu.nickname AS author,	" +
        "	    DATE_FORMAT(	" +
        "	      vdd.create_time,	" +
        "	      '%Y-%m-%d %H:%i:%s'	" +
        "	    ) AS tmpl_time,	" +
        "	    fav.show_type_id,	" +
        "	    CONCAT(	" +
        "	      '收藏于',	" +
        "	      DATE_FORMAT(fav.create_time, '%Y-%m-%d')	" +
        "	    ) AS `time`,	" +
        "	    fav.create_time,	" +
        "	    IFNULL(yst.title, '') AS typeDesc  	" +
        "	  FROM	" +
        "	    yjx.yjx_uni_items yui,	" +
        "	    itbour.video_design_doc vdd,	" +
        "	    itbour.itb_user iu,	" +
        "	    itbour.tg_size ts,	" +
        "	    yjx.yjx_favorite fav,	" +
        "	    yjx.yjx_show_type yst	" +
        "	  WHERE yui.item_type = 30	" +
        "	    AND fav.user_id = "+userId+"	" +
        "	    AND fav.uni_item_id = yui.uni_item_id	" +
        "	    AND yui.item_id = vdd.design_id	" +
        "	    AND yst.st_id = fav.show_type_id	" +
        "	    AND vdd.user_id = iu.user_id	" +
        "	    AND vdd.size_id = ts.size_id	" +
        "	    AND yst.del_flg = 0	" +
        "	    AND vdd.del_flg = 0	" +
        "	    AND yui.del_flg = 0	" +
        "	    AND iu.del_flg = 0	" +
        "	    AND ts.del_flg = 0	" +
        "	    AND fav.del_flg = 0	" +
        "	    AND vdd.publish = 1	" +
        "	  UNION ALL	" +
        "	  SELECT	" +
        "	    yui.uni_item_id AS id,	" +
        "	    tdd.design_name AS `name`,	" +
        "	    '1' AS opType,	" +
        "	    tdp.thumb,	" +
        "	    ts.width AS w,	" +
        "	    ts.height AS h,	" +
        "	    iu.nickname AS author,	" +
        "	    DATE_FORMAT(	" +
        "	      tdd.create_time,	" +
        "	      '%Y-%m-%d %H:%i:%s'	" +
        "	    ) AS tmpl_time,	" +
        "	    fav.show_type_id,	" +
        "	    CONCAT(	" +
        "	      '收藏于',	" +
        "	      DATE_FORMAT(fav.create_time, '%Y-%m-%d')	" +
        "	    ) AS `time`,	" +
        "	    fav.create_time,	" +
        "	    IFNULL(yst.title, '') AS typeDesc	" +
        "	  FROM	" +
        "	    yjx.yjx_uni_items yui,	" +
        "	    itbour.tg_design_doc tdd,	" +
        "	    itbour.tg_design_page tdp,	" +
        "	    itbour.itb_user iu,	" +
        "	    itbour.tg_size ts,	" +
        "	    yjx.yjx_favorite fav,	" +
        "	    yjx.yjx_show_type yst  	" +
        "	  WHERE yui.item_type = 10	" +
        "	    AND fav.user_id = "+userId+"	" +
        "	    AND fav.uni_item_id = yui.uni_item_id	" +
        "	    AND yui.item_id = tdd.design_id	" +
        "	    AND tdd.size_id = ts.size_id	" +
        "	    AND tdd.user_id = iu.user_id	" +
        "	    AND tdd.design_id = tdp.design_id	" +
        "	    AND yst.st_id = fav.show_type_id	" +
        "	    AND yst.del_flg = 0	" +
        "	    AND tdp.page_index = 0	" +
        "	    AND tdd.del_flg = 0	" +
        "	    AND yui.del_flg = 0	" +
        "	    AND tdp.del_flg = 0	" +
        "	    AND iu.del_flg = 0	" +
        "	    AND ts.del_flg = 0	" +
        "	    AND fav.del_flg = 0	" +
        "	    AND tdd.publish = 1) res	" +
        "	    left join yjx.yjx_uni_tmpl_stats uts	" +
        "	    on uts.uni_item_id = res.id	" +
        "	    and uts.del_flg = 0	" +
        "	ORDER BY res.create_time DESC	" ;
    if (typeof pageNum !== 'undefined' && pageNum !== null &&
        typeof pageSize !== 'undefined' && pageSize !== null)
    {
        var skipCnt = Number(pageNum||'0') * Number(pageSize||'0');
        sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
    }
    return sql;
}

/**
 * 获取查询 用户视频收藏（列表/数量 ）的 sql
 *
 * @author 毛凯
 * @date   2013-3-1
 *
 * @param bForCnt true 获取用去收藏列表个数的 sql, false 标记获取列表的 sql
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param opType 2为视频1为设计
 *
 * @return 对应类型的 sql
 * */
function sql_getUserVideoFavList(bForCnt, userId, pageNum, pageSize,opType) {

    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(0) as count ';
    } else  {
        sql +="	select	" +
            "	  res.*,	" +
            "	  IFNULL(uts.show_apply_cnt, 0) AS useCounts	"
    }
    sql +="	from	" +
        "	  (SELECT	" +
        "	    yui.uni_item_id AS id,	" +
        "	    vdd.design_name AS `name`,	" +
        "	    '2' AS opType,	" +
        "	    vdd.theme_thumb AS thumb,	" +
        "	    ts.width AS w,	" +
        "	    ts.height AS h,	" +
        "	    iu.nickname AS author,	" +
        "	    DATE_FORMAT(	" +
        "	      vdd.create_time,	" +
        "	      '%Y-%m-%d %H:%i:%s'	" +
        "	    ) AS tmpl_time,	" +
        "	    fav.show_type_id,	" +
        "	    CONCAT(	" +
        "	      '收藏于',	" +
        "	      DATE_FORMAT(fav.create_time, '%Y-%m-%d')	" +
        "	    ) AS `time`,	" +
        "	    fav.create_time,	" +
        "	    IFNULL(yst.title, '') AS typeDesc,	" +
        "	    vdd.duration AS duration	" +
        "	  FROM	" +
        "	    yjx.yjx_uni_items yui,	" +
        "	    itbour.video_design_doc vdd,	" +
        "	    itbour.itb_user iu,	" +
        "	    itbour.tg_size ts,	" +
        "	    yjx.yjx_favorite fav,	" +
        "	    yjx.yjx_show_type yst	" +
        "	  WHERE yui.item_type = 30	" +
        "	    AND fav.user_id = "+userId+"	" +
        "	    AND fav.uni_item_id = yui.uni_item_id	" +
        "	    AND yui.item_id = vdd.design_id	" +
        "	    AND yst.st_id = fav.show_type_id	" +
        "	    AND vdd.user_id = iu.user_id	" +
        "	    AND vdd.size_id = ts.size_id	" +
        "	    AND yst.del_flg = 0	" +
        "	    AND vdd.del_flg = 0	" +
        "	    AND yui.del_flg = 0	" +
        "	    AND iu.del_flg = 0	" +
        "	    AND ts.del_flg = 0	" +
        "	    AND fav.del_flg = 0	" +
        "	    AND vdd.publish = 1	" +
        "	  UNION	" +
        "	  ALL	" +
        "	  SELECT	" +
        "	    yui.uni_item_id AS id,	" +
        "	    tdd.design_name AS `name`,	" +
        "	    '1' AS opType,	" +
        "	    tdp.thumb,	" +
        "	    ts.width AS w,	" +
        "	    ts.height AS h,	" +
        "	    iu.nickname AS author,	" +
        "	    DATE_FORMAT(	" +
        "	      tdd.create_time,	" +
        "	      '%Y-%m-%d %H:%i:%s'	" +
        "	    ) AS tmpl_time,	" +
        "	    fav.show_type_id,	" +
        "	    CONCAT(	" +
        "	      '收藏于',	" +
        "	      DATE_FORMAT(fav.create_time, '%Y-%m-%d')	" +
        "	    ) AS `time`,	" +
        "	    fav.create_time,	" +
        "	    IFNULL(yst.title, '') AS typeDesc,	" +
        "	    0 AS duration	" +
        "	  FROM	" +
        "	    yjx.yjx_uni_items yui,	" +
        "	    itbour.tg_design_doc tdd,	" +
        "	    itbour.tg_design_page tdp,	" +
        "	    itbour.itb_user iu,	" +
        "	    itbour.tg_size ts,	" +
        "	    yjx.yjx_favorite fav,	" +
        "	    yjx.yjx_show_type yst	" +
        "	  WHERE yui.item_type = 10	" +
        "	    AND fav.user_id = "+userId+"	" +
        "	    AND fav.uni_item_id = yui.uni_item_id	" +
        "	    AND yui.item_id = tdd.design_id	" +
        "	    AND tdd.size_id = ts.size_id	" +
        "	    AND tdd.user_id = iu.user_id	" +
        "	    AND tdd.design_id = tdp.design_id	" +
        "	    AND yst.st_id = fav.show_type_id	" +
        "	    AND yst.del_flg = 0	" +
        "	    AND tdp.page_index = 0	" +
        "	    AND tdd.del_flg = 0	" +
        "	    AND yui.del_flg = 0	" +
        "	    AND tdp.del_flg = 0	" +
        "	    AND iu.del_flg = 0	" +
        "	    AND ts.del_flg = 0	" +
        "	    AND fav.del_flg = 0	" +
        "	    AND tdd.publish = 1) res	" +
        "	  left join yjx.yjx_uni_tmpl_stats uts	" +
        "	    on uts.uni_item_id = res.id	" +
        "	    and uts.del_flg = 0	" +
        "	where res.opType IN ("+opType+")	" +
        "	ORDER BY res.create_time DESC	" ;
    if(!bForCnt){
        if (typeof pageNum !== 'undefined' && pageNum !== null &&
            typeof pageSize !== 'undefined' && pageSize !== null)
        {
            var skipCnt = Number(pageNum||'0') * Number(pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
        }
    }
    return sql;
}

/**
 * 获取用户视频收藏列表
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param opType 1,设计  2视频
 * @param callback 回调
 *           err: 查询失败
 *           results: 用户对应收藏列表
 *
 * */
YjxFavoriteModel.prototype.getUserVideoFavList = function (userId, pageNum, pageSize,opType,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserVideoFavList(false, userId, pageNum, pageSize,opType);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取用户视频收藏个数
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param opType  1,设计 2视频
 * @param callback 回调
 *           err: 查询失败
 *           count: 用户收藏列表数量
 *
 * */
YjxFavoriteModel.prototype.getUserVideoFavListCnt = function (userId, pageNum, pageSize,opType,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavListCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserVideoFavList(true, userId, pageNum, pageSize,opType);
        console.log(sql);

        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavListCnt] queryErr' + queryErr);
                return callback(queryErr, null);
            }
            if (results && results[0]) {
                return callback(queryErr, results[0].count);
            }
            return callback(queryErr,null);
        });
    })

};
// 导出
module.exports = YjxFavoriteModel;